﻿using Common;
using DevExpress.XtraEditors;
using DLL;
using NursingDocumentInfoSystem;
using NursingFormSystem.BLL;
using NursingFormSystem.Common;
using NursingFormSystem.Model;
using NursingFormSystem.Notice;
using SQLDLL;
using System;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace NursingFormSystem.NursingRecordSheet
{
    public partial class AddSheet : Form
    {
        #region 变量声明

        public NursingFormSystem.NurFormsService.NursingForm formService = new NursingFormSystem.NurFormsService.NursingForm();
        NursingFormRecord record = new NursingFormRecord();
        string Id;
        PatientInfo PatientInfo;
        Tb_User LoginUser;
        Random rd = new Random();
        #endregion

        #region 构造函数
        public AddSheet(Tb_User loginUser, PatientInfo patientInfo, string id)
        {
            InitializeComponent();
            //构造函数
            this.PatientInfo = patientInfo;
            this.LoginUser = loginUser;
            this.Id = id;
            //绑定数据
            BindInfo(id);
            ElectronicSignature();
        }
        public AddSheet(string[] loginUser, string[] patientInfo)
        {
            InitializeComponent();
            //构造函数
            this.PatientInfo = ArrayToObject.ArrayToPatientInfo(patientInfo);
            this.LoginUser = ArrayToObject.ArrayToLoginUser(loginUser);
            this.Id = string.Empty;
            //绑定数据
            BindInfo(this.Id);
            ElectronicSignature();
        }
        public AddSheet(string[] loginUser, string[] patientInfo, string id)
        {
            InitializeComponent();
            //构造函数
            this.PatientInfo = ArrayToObject.ArrayToPatientInfo(patientInfo);
            this.LoginUser = ArrayToObject.ArrayToLoginUser(loginUser);
            this.Id = id;
            //绑定数据
            BindInfo(this.Id);
            ElectronicSignature();
        }
        /// <summary>
        /// 初始化加载印章图片
        /// </summary>
        private void ElectronicSignature()
        {
            ElectronicSignature es = new ElectronicSignature(LoginUser);
            es.SearchElectronicSignatureImage(Base.ESSwitch, LoginUser, txtE_Signature, picElectronicSignature, txtE_Signature.Location);
        }

        private void BindInfo(string id)
        {
            txtE_Signature.Text = LoginUser.UserName;
            dateriqi.DateTime = DateTime.Now;   //显示当前日期
            timeE_Time.EditValue = DateTime.Now.ToString("HH:mm");//显示时间

            if (string.IsNullOrEmpty(id)) return;
            string sql = string.Format("SELECT TOP 1 NursingFormData FROM NursingFormRecord(NOLOCK) WHERE Id='{0}'", Id);
            DataSet ds = SqlHelper.ExecuteDataset(sql);
            if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0) return;
            DataTable tab = ds.Tables[0];
            var NursingFormData = Convert.ToString(tab.Rows[0]["NursingFormData"]);
            ClinicalCare cc = new ClinicalCare();
            cc = XmlUtil.XMLToObject<ClinicalCare>(NursingFormData, Encoding.UTF8);
            dateriqi.Text = cc.RiQi;    //日期
            timeE_Time.EditValue = DateTimeHelper.HHmmssToHHmm(cc.ShiJian);   //时间
            texttiwen.Text = cc.TiWen;  //体温
            textmaibo.Text = cc.MaiBo;  //脉搏
            textxinlv.Text = cc.XinLv;  //心率
            texthuxi.Text = cc.HuXi;    //呼吸
            textxueya.Text = cc.XueYa.Split('/')[0];  //血压
            textxueya2.Text = cc.XueYa.Split('/')[1];  //血压2
            textSPO2N.Text = cc.Spo;    //SPO2N
            checkEditfanshen.Checked = cc.FanShen == "1";//翻身
            comShenZhi.Text = cc.ShenZhi;//神志
            textzuo.Text = cc.TongKongDaXiaoZuo;//瞳孔大小左
            textyou.Text = cc.TongKongDaXiaoYou;//瞳孔大小右
            comduiguangzuo.Text = cc.TongKongDuiGuangZuo;//对光反射左
            comduiguangyou.Text = cc.TongKongDuiGuangYou;//对光反射右
            //排出流体量 # 分割 多个名称,分割
            txtpaichuyetiliang.Text = cc.PaiChuYeLiangMingCheng + "#" + cc.PaiChuYeLiangLiang;
            //输入流体及食物 示例 
            //单个 10%葡萄糖#44#静推
            //多个 10%葡萄糖,木糖醇#10,100#静推,静脉泵入
            txtshuruyeti.Text = cc.ShuRuYeTiMingCheng + "#" + cc.ShuRuYeTiLiang + "#" + cc.ShuRuYeTiTuJing;
            memobingqingcuoshi.EditValue = cc.BingQingZhiLiaoJiHuLiCuoShi;//护理措施
            txtE_Signature.Text = cc.QianMing;  //签名
            chkNewPage.Checked = !string.IsNullOrEmpty(cc.IsNewPageFlag) && cc.IsNewPageFlag.Equals("Y");
            txtsyncSN.Text = cc.syncSN;//同步海泰的数据标识，用于海泰数据同步的CRUD
        }
        #endregion

        #region 保存
        private void simpleButtonbaocun_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(dateriqi.Text.Trim()))
                dateriqi.DateTime = DateTime.Now;

            ClinicalCare cc = new ClinicalCare();
            cc.RiQi = dateriqi.Text;    //日期
            cc.ShiJian = DateTimeTran.TimeFillZero(timeE_Time.Text);  //时间
            cc.TiWen = texttiwen.Text;  //体温
            cc.MaiBo = textmaibo.Text;  //脉搏
            cc.XinLv = textxinlv.Text;  //心率
            cc.HuXi = texthuxi.Text;    //呼吸
            cc.XueYa = textxueya.Text + "/" + textxueya2.Text;  //血压
            cc.Spo = textSPO2N.Text;    //SPO2N
            cc.FanShen = checkEditfanshen.Checked ? "1" : "0";//翻身
            cc.ShenZhi = comShenZhi.Text;//神志
            cc.TongKongDaXiaoZuo = textzuo.Text;//瞳孔大小左
            cc.TongKongDaXiaoYou = textyou.Text;//瞳孔大小右
            cc.TongKongDuiGuangZuo = comduiguangzuo.Text;//对光反射左
            cc.TongKongDuiGuangYou = comduiguangyou.Text;//对光反射右
            //排出流体量 
            cc.PaiChuYeLiangMingCheng = txtpaichuyetiliang.Text.Split('#')[0];
            cc.PaiChuYeLiangLiang = txtpaichuyetiliang.Text.Split('#')[1];
            //输入流体及食物 示例 
            //单个 10%葡萄糖#44#静推
            //多个 10%葡萄糖,木糖醇#10,100#静推,静脉泵入
            cc.ShuRuYeTiMingCheng = txtshuruyeti.Text.Split('#')[0];
            cc.ShuRuYeTiLiang = txtshuruyeti.Text.Split('#')[1];
            cc.ShuRuYeTiTuJing = txtshuruyeti.Text.Split('#')[2];
            cc.BingQingZhiLiaoJiHuLiCuoShi = memobingqingcuoshi.Text;//护理措施            
            if (string.IsNullOrEmpty(this.Id))
                cc.QianMing = LoginUser.UserName;
            else
                cc.QianMing = txtE_Signature.Text;

            cc.IsNewPageFlag = chkNewPage.Checked ? "Y" : "N";

            cc.FormId = (int)FormType.NurseForm;
            cc.FormName = EnumHelper.GetDescription(FormType.NurseForm);
            cc.syncSN = txtsyncSN.Text;

            record.NursingFormData = XmlUtil.ObjectToXML(cc, Encoding.UTF8);
            record.FormId = cc.FormId;//表单ID
            record.FormName = cc.FormName;//表单NAME
            record.PatientId = PatientInfo.PATIENT_ID;//住院号
            record.VisitId = PatientInfo.VISIT_ID;//住院次数
            record.PatientName = PatientInfo.PATIENT_NAME;//患者名称
            record.BedNo = PatientInfo.BED_NO;//床号
            string rst = System.DateTime.Now.ToString("yyyyMMddHHmmss") + rd.Next(100, 10000).ToString();//用rad生成大于等于1000，小于等于9999的随机数
            if (Id == "")//修正转科或者出院后修改病人导致病区错误
            {
                //新增的时候这俩为空值
                cc.Group12 = string.Empty;
                cc.Group24 = string.Empty;

                record.DepartmentId = LoginUser.DepartmentCode;//科室号    
                record.DepartmentName = PatientInfo.DEPARTMENT_NAME.Trim();//科室名称
                record.AreaId = LoginUser.DepartmentCode;//病区编号
                record.AreaName = PatientInfo.DEPARTMENT_NAME.Trim();//病区名称
                record.syncSN = rst;
            }
            record.AssessmentDate = Convert.ToDateTime(dateriqi.DateTime.ToString("yyyy-MM-dd") + " " + timeE_Time.Text);//日期  
            record.Id = Id == "" ? 0 : Convert.ToInt32(Id);

            #region xmldata
            string[] temp = Regex.Split(txtshuruyeti.Text, "#", RegexOptions.IgnoreCase);
            if (temp.Length < 3)
            {
                XtraMessageBox.Show("流入部分未填写，如无流入部分，请填写##");
                return;
            }
            string Intakename = temp[0];
            string Intakevalue = temp[1];
            string Intakeway = temp[2];
            string[] temp2 = Regex.Split(txtpaichuyetiliang.Text, "#", RegexOptions.IgnoreCase);
            if (temp2.Length < 2)
            {
                XtraMessageBox.Show("流出部分未填写，如无流出部分，请填写#");
                return;
            }
            string Dischargename = temp2[0];
            string Dischargevalue = temp2[1];
            StringBuilder data = new StringBuilder();
            data.Append("<NursingRecordDocument>");
            data.AppendFormat("<Temper>{0}</Temper>", texttiwen.Text);
            data.AppendFormat("<Pulse>{0}</Pulse>", textmaibo.Text);
            data.AppendFormat("<HeartRate>{0}</HeartRate>", textxinlv.Text);
            data.AppendFormat("<Breath>{0}</Breath>", texthuxi.Text);
            data.AppendFormat("<Systolicpressure>{0}</Systolicpressure>", textxueya.Text);
            data.AppendFormat("<Diastolicpressure>{0}</Diastolicpressure>", textxueya2.Text);
            data.AppendFormat("<Spo2>{0}</Spo2>", textSPO2N.Text);
            data.AppendFormat("<StandUp>{0}</StandUp>", checkEditfanshen.Checked ? "√" : string.Empty);
            data.AppendFormat("<Intakename>{0}</Intakename>", Intakename);
            data.AppendFormat("<Intakevalue>{0}</Intakevalue>", Intakevalue);
            data.AppendFormat("<Intakediway>{0}</Intakediway>", Intakeway);
            data.AppendFormat("<Dischargename>{0}</Dischargename>", Dischargename);
            data.AppendFormat("<Dischargevalue>{0}</Dischargevalue>", Dischargevalue);
            data.AppendFormat("<Tendcontent>{0}</Tendcontent>", memobingqingcuoshi.Text);
            data.AppendFormat("<NursName>{0}</NursName>", txtE_Signature.Text);
            data.Append("<specialbilleles>");

            data.Append("<specialbillele>");
            data.Append("<option>1</option>");//是否是下拉值（0为文本框，1为下拉值）
            data.Append("<eleid>HT51.02.501</eleid>");
            data.Append("<elename>神志</elename>");//HT51.02.501	神志	下拉
            data.AppendFormat("<elevalue>{0}</elevalue>", comShenZhi.Text);//元素值
            data.Append("</specialbillele>");
            data.Append("<specialbillele>");

            data.Append("<option>0</option>");//是否是下拉值（0为文本框，1为下拉值）
            data.Append("<eleid>HT51.02.885</eleid>");
            data.Append("<elename>瞳孔大小(左)mm</elename>");//HT51.02.885	瞳孔大小(左)	文本
            data.AppendFormat("<elevalue>{0}</elevalue>", textzuo.Text);//元素值
            data.Append("</specialbillele>");
            data.Append("<specialbillele>");

            data.Append("<option>0</option>");//是否是下拉值（0为文本框，1为下拉值）
            data.Append("<eleid>HT51.02.886</eleid>");
            data.Append("<elename>瞳孔大小(右)mm</elename>");//HT51.02.886	瞳孔大小(右)	文本
            data.AppendFormat("<elevalue>{0}</elevalue>", textyou.Text);//元素值
            data.Append("</specialbillele>");

            data.Append("<specialbillele>");
            data.Append("<option>1</option>");//是否是下拉值（0为文本框，1为下拉值）
            data.Append("<eleid>HT51.02.1139</eleid>");
            data.Append("<elename>瞳孔对光反射（左）</elename>");//HT51.02.1139	瞳孔对光反射（左）	下拉
            data.AppendFormat("<elevalue>{0}</elevalue>", comduiguangzuo.Text);//元素值
            data.Append("</specialbillele>");

            data.Append("<specialbillele>");
            data.Append("<option>1</option>");//是否是下拉值（0为文本框，1为下拉值）
            data.Append("<eleid>HT51.02.1140</eleid>");
            data.Append("<elename>瞳孔对光反射（右）</elename>");//HT51.02.1140	瞳孔对光反射（右）	下拉
            data.AppendFormat("<elevalue>{0}</elevalue>", comduiguangyou.Text);//元素值
            data.Append("</specialbillele>");

            data.Append("<specialbillele>");
            data.Append("<option>0</option>");//是否是下拉值（0为文本框，1为下拉值）
            data.Append("<eleid>HT51.02.646</eleid>");
            data.Append("<elename>病情观察及措施</elename>");//HT51.02.646	病情观察及措施	文本
            data.AppendFormat("<elevalue>{0}</elevalue>", memobingqingcuoshi.Text);//元素值
            data.Append("</specialbillele>");

            data.Append("</specialbilleles>");
            data.Append("</NursingRecordDocument>");
            #endregion

            var ret = formService.SetNursingFormRecord(Newtonsoft.Json.JsonConvert.SerializeObject(record));
            if (ret.Code == 1)
            {
                if (Base.ESSwitch.Equals("on"))//电签开始
                {
                    //TODO:电签接口提交
                    string extraInfo = "<?xml version=\"1.0\" encoding=\"UTF-16\"?><root><sign_sys>{0}</sign_sys><title>{1}</title><patient_id>{2}</patient_id><patient_name>{3}</patient_name><emr_id>{4}</emr_id><emr_catalog>{5}</emr_catalog><his_id>{6}</his_id><event_no>{7}</event_no><visit_number>{8}</visit_number><dept_name>{9}</dept_name><prescribe_number>{10}</prescribe_number><prescribe_sub_number>{11}</prescribe_sub_number><prescribe_operation>医嘱操作（发送、校对、停止、作废）或门诊处方操作（发送）</prescribe_operation><radiotherapy_id>放疗号</radiotherapy_id><process_name>CT定位申请单审核</process_name><process_time>CT定位申请单审核时间</process_time><extend_value_1>备用扩展1</extend_value_1><extend_value_2>备用扩展2</extend_value_2><extend_value_3>备用扩展3</extend_value_3><extend_value_4>备用扩展4</extend_value_4><extend_value_5>备用扩展5</extend_value_5><extend_value_6>备用扩展6</extend_value_6><extend_value_7>备用扩展7</extend_value_7><extend_value_8>备用扩展8</extend_value_8><extend_value_9>备用扩展9</extend_value_9></root>";
                    extraInfo = string.Format(extraInfo, EnumHelper.GetDescription(FormType.NurseForm) + (record.Id > 0 ? "-更新" : "-新增"), EnumHelper.GetDescription(FormType.NurseForm), record.PatientId, record.PatientName, record.Id, record.FormId, "", record.PatientId, record.VisitId, LoginUser.DepartmentName, record.PatientId, record.PatientId);
                    ElectronicSignature es = new ElectronicSignature(LoginUser);
                    bool flag = es.GetElectronicSignatureImage(es, record.NursingFormData, extraInfo, ((int)FormType.NurseForm).ToString(), EnumHelper.GetDescription(FormType.NurseForm), PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID);
                    if (!flag) { MessageBox.Show("电子签名失败"); return; }
                }//电签结束

                MessageBox.Show(ret.M);

                #region 上传海泰
                if (Base.ESSwitchHT == "1")
                {
                    SynchroBLL synchro = new SynchroBLL();
                    ClinicalNursinguser cn = new ClinicalNursinguser();
                    cn.PatientId = record.PatientId;
                    cn.PatientName = record.PatientName;
                    cn.DepId = record.DepartmentId;
                    cn.DepName = record.DepartmentName;
                    cn.AreaId = record.AreaId;
                    cn.AreaName = record.AreaName;
                    cn.data = data.ToString();
                    cn.Date = Convert.ToDateTime(record.AssessmentDate).ToString("yyyy-MM-dd");
                    cn.Time = Convert.ToDateTime(record.AssessmentDate).ToString("HH:mm");
                    cn.NursName = txtE_Signature.Text;
                    cn.VisitId = record.VisitId;
                    cn.UpdateuserId = this.LoginUser.UserId;
                    cn.UpdateuserName = this.LoginUser.UserName;
                    if (string.IsNullOrEmpty(this.Id))
                    {
                        cn.syncSN = rst;
                        synchro.clinicalNursingInfoAsyncToEMRDelegateMethod(cn, "001", "1");
                    }
                    else
                    {
                        cn.syncSN = txtsyncSN.Text;
                        synchro.clinicalNursingInfoAsyncToEMRDelegateMethod(cn, "001", "2");
                    }
                }
                #endregion

                this.DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show(ret.M);
            }
        }
        #endregion

        #region 取消
        private void simpleButtonquxiao_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }
        #endregion

        #region 双击病情治疗及护理措施
        private void memobingqingcuoshi_DoubleClick(object sender, EventArgs e)
        {
            NursingMeasure nursingMeasure = new NursingMeasure(memobingqingcuoshi.Text, LoginUser.DepartmentCode);
            nursingMeasure.ShowDialog();
            if (nursingMeasure.TTT.Trim() != "")
            {
                memobingqingcuoshi.Text = nursingMeasure.TTT;
            }
        }
        #endregion

        #region 排出液量
        private void txtpaichuyetiliang_DoubleClick(object sender, EventArgs e)
        {
            using (NursingSummarySelForm4 NSSF = new NursingSummarySelForm4(txtpaichuyetiliang.Text, PatientInfo.PATIENT_ID))
            {
                NSSF.ShowDialog();
                if (NSSF.DialogResult == DialogResult.OK)
                    txtpaichuyetiliang.Text = NSSF.TempStr;
                else
                    txtpaichuyetiliang.Text = NSSF.str_ReturnSummary;
            }
        }
        #endregion

        #region 双击输入液体及食物
        private void txtshuruyeti_DoubleClick(object sender, EventArgs e)
        {
            using (NursingSummarySelForm3 NSSF = new NursingSummarySelForm3(txtshuruyeti.Text, PatientInfo.PATIENT_ID))
            {
                NSSF.ShowDialog();
                if (NSSF.DialogResult == DialogResult.OK)
                    txtshuruyeti.Text = NSSF.TempStr;
                else
                    txtshuruyeti.Text = NSSF.str_ReturnSummary;
            }
        }
        #endregion

        #region 设置 enter键当做Tab切换
        private void TemperatureEdit1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SendKeys.SendWait("{Tab}");
            }
        }
        #endregion

        #region 体温导入
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            TemperatureIn x = new TemperatureIn(this.PatientInfo.PATIENT_ID, this.PatientInfo.VISIT_ID.ToString());
            x.ShowDialog();
            if (x.DialogResult == DialogResult.Yes)
            {
                texttiwen.Text = x.tiwen;
                textmaibo.Text = x.maibo;
                textxinlv.Text = x.xinlv;
                texthuxi.Text = x.huxi;
                textxueya.Text = x.xueya1;
                textxueya2.Text = x.xueya2;
            }
        }
        #endregion

        #region 查看医嘱
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            PatientOrders xx = new PatientOrders(PatientInfo.PATIENT_ID, PatientInfo.VISIT_ID.ToString(), LoginUser.DepartmentCode);
            xx.ShowDialog();
            if (xx.DialogResult == DialogResult.Yes)
            {
                string[] temp = Regex.Split(txtshuruyeti.Text, "#", RegexOptions.IgnoreCase);
                string[] tempname = Regex.Split(temp[0], ",", RegexOptions.IgnoreCase);
                string[] tempnum = Regex.Split(temp[1], ",", RegexOptions.IgnoreCase);
                string[] tempway = Regex.Split(temp[2], ",", RegexOptions.IgnoreCase);
                string TempStr = "";
                for (int i = 0; i < tempname.Length; i++)
                {
                    TempStr += tempname[i].ToString();
                    if (tempname[i].ToString().Trim().Length != 0)
                    {
                        TempStr += ",";
                    }
                }
                for (int i = 0; i < xx.NameList.Count; i++)
                {
                    TempStr += xx.NameList[i].ToString();
                    TempStr += ",";
                }
                TempStr = TempStr.Substring(0, TempStr.Length - 1);
                TempStr += "#";
                for (int i = 0; i < tempnum.Length; i++)
                {
                    TempStr += tempnum[i].ToString();
                    if (tempnum[i].ToString().Trim().Length != 0)
                    {
                        TempStr += ",";
                    }
                }
                for (int i = 0; i < xx.NumList.Count; i++)
                {
                    TempStr += xx.NumList[i].ToString();
                    TempStr += ",";
                }
                TempStr = TempStr.Substring(0, TempStr.Length - 1);
                TempStr += "#";
                for (int i = 0; i < tempway.Length; i++)
                {
                    TempStr += tempway[i].ToString();
                    if (tempway[i].ToString().Trim().Length != 0)
                    {
                        TempStr += ",";
                    }
                }
                for (int i = 0; i < xx.WayList.Count; i++)
                {
                    TempStr += xx.WayList[i].ToString();
                    TempStr += ",";
                }
                TempStr = TempStr.Substring(0, TempStr.Length - 1);
                txtshuruyeti.Text = TempStr;
            }
        }
        #endregion

        private void BtnMyTemplate_Click(object sender, EventArgs e)
        {
            string[] UserParam = { LoginUser.UserId };
            NoticeMain noticefrm = new NoticeMain(UserParam);
            noticefrm.WindowState = FormWindowState.Normal;
            noticefrm.Show();
        }
    }
}